{% extends "base.html" %}

{% block title %}高级分析 - SurveyAnalyzer{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item">
            <a href="{{ url_for('main.index') }}">
                <i class="fas fa-home me-1"></i>
                首页
            </a>
        </li>
        <li class="breadcrumb-item">
            <a href="{{ url_for('main.analyze', filename=filename) }}">
                <i class="fas fa-chart-bar me-1"></i>
                数据分析
            </a>
        </li>
        <li class="breadcrumb-item active" aria-current="page">
            <i class="fas fa-brain me-1"></i>
            高级分析
        </li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 分析选项面板 -->
    <div class="col-md-3 mb-4">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-cogs me-2"></i>
                    分析选项
                </h6>
            </div>
            <div class="card-body">
                <!-- PCA分析选项 -->
                <div class="mb-3">
                    <label class="form-label">分析类型</label>
                    <div class="form-control-plaintext">
                        <i class="fas fa-chart-line me-2"></i>
                        主成分分析 (PCA)
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">主成分数量</label>
                    <input type="number" class="form-control" id="nComponents" min="1" max="10" value="2">
                    <small class="form-text text-muted">留空则自动确定</small>
                </div>
                
                <div class="mb-3">
                    <label class="form-label">方差解释阈值</label>
                    <input type="number" class="form-control" id="varianceThreshold" min="0.1" max="1" step="0.05" value="0.95">
                    <small class="form-text text-muted">用于自动确定主成分数量</small>
                </div>
                
                <button class="btn btn-primary w-100" onclick="runAnalysis()">
                    <i class="fas fa-play me-1"></i>
                    开始分析
                </button>
            </div>
        </div>
        
        <!-- 数据信息 -->
        <div class="card mt-3">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>
                    数据信息
                </h6>
            </div>
            <div class="card-body" id="dataInfo">
                <div class="text-center">
                    <div class="spinner-border spinner-border-sm" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2 mb-0">加载数据信息...</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 分析结果面板 -->
    <div class="col-md-9">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-chart-line me-2"></i>
                    分析结果
                </h5>
                <div>
                    <button class="btn btn-outline-secondary btn-sm" onclick="exportResults()" id="exportBtn" style="display: none;">
                        <i class="fas fa-download me-1"></i>
                        导出结果
                    </button>
                </div>
            </div>
            <div class="card-body" id="resultsContainer">
                <div class="text-center text-muted py-5">
                    <i class="fas fa-chart-line fa-3x mb-3"></i>
                    <h5>选择分析类型并点击"开始分析"</h5>
                    <p>支持主成分分析、异常检测、时间序列分析等多种高级分析方法</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 加载模态框 -->
<div class="modal fade" id="loadingModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body text-center py-4">
                <div class="spinner-border text-primary mb-3" role="status">
                    <span class="visually-hidden">分析中...</span>
                </div>
                <h5>正在进行高级分析...</h5>
                <p class="text-muted mb-0">请稍候，这可能需要几秒钟</p>
            </div>
        </div>
    </div>
</div>

<style>
.analysis-options {
    transition: all 0.3s ease;
}

.result-section {
    margin-bottom: 2rem;
    padding: 1.5rem;
    border: 1px solid #dee2e6;
    border-radius: 0.5rem;
    background: #f8f9fa;
}

.result-section h6 {
    color: #495057;
    border-bottom: 2px solid #007bff;
    padding-bottom: 0.5rem;
    margin-bottom: 1rem;
}

.metric-card {
    background: white;
    border: 1px solid #e9ecef;
    border-radius: 0.375rem;
    padding: 1rem;
    text-align: center;
    transition: transform 0.2s ease;
}

.metric-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.metric-value {
    font-size: 1.5rem;
    font-weight: bold;
    color: #007bff;
}

.metric-label {
    font-size: 0.875rem;
    color: #6c757d;
    margin-top: 0.25rem;
}

.feature-importance {
    max-height: 300px;
    overflow-y: auto;
}

.feature-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.5rem 0;
    border-bottom: 1px solid #f0f0f0;
}

.feature-item:last-child {
    border-bottom: none;
}

.feature-bar {
    height: 20px;
    background: linear-gradient(90deg, #007bff, #0056b3);
    border-radius: 10px;
    transition: width 0.3s ease;
}

.plot-container {
    min-height: 400px;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
    margin-bottom: 1rem;
}

.anomaly-point {
    color: #dc3545;
    font-weight: bold;
}

.normal-point {
    color: #28a745;
}
</style>

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script>
const filename = '{{ filename }}';
let currentResults = null;
let dataInfo = null;

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    loadDataInfo();
    // PCA选项始终显示，无需切换
});

// 加载数据信息
function loadDataInfo() {
    fetch(`/api/data/${filename}`)
    .then(response => response.json())
    .then(data => {
        if (data.success !== false) {
            dataInfo = data;
            displayDataInfo(data);
            populateColumnOptions(data);
        } else {
            console.error('Failed to load data info:', data.error);
        }
    })
    .catch(error => {
        console.error('Error loading data info:', error);
        document.getElementById('dataInfo').innerHTML = `
            <div class="text-center text-danger">
                <i class="fas fa-exclamation-triangle"></i>
                <p class="mt-2 mb-0">加载失败</p>
            </div>
        `;
    });
}

// 显示数据信息
function displayDataInfo(info) {
    const container = document.getElementById('dataInfo');
    
    container.innerHTML = `
        <div class="row g-2">
            <div class="col-6">
                <div class="text-center">
                    <div class="fw-bold text-primary">${info.shape ? info.shape[0] : 'N/A'}</div>
                    <small class="text-muted">样本数</small>
                </div>
            </div>
            <div class="col-6">
                <div class="text-center">
                    <div class="fw-bold text-success">${info.shape ? info.shape[1] : 'N/A'}</div>
                    <small class="text-muted">特征数</small>
                </div>
            </div>
            <div class="col-6">
                <div class="text-center">
                    <div class="fw-bold text-info">${info.dtypes ? Object.keys(info.dtypes).length : 0}</div>
                    <small class="text-muted">数据类型</small>
                </div>
            </div>
            <div class="col-6">
                <div class="text-center">
                    <div class="fw-bold text-warning">${info.missing_values || 0}</div>
                    <small class="text-muted">缺失值</small>
                </div>
            </div>
        </div>
    `;
}

// PCA不需要选择特定列，使用所有数值列
function populateColumnOptions(info) {
    // PCA分析会自动使用所有数值列，无需手动选择
}

// 更新分析选项（简化为PCA）
function updateAnalysisOptions() {
    // PCA选项始终显示，无需切换
}

// 强制隐藏模态框的通用函数
function forceHideModal() {
    const loadingModal = document.getElementById('loadingModal');
    if (loadingModal) {
        // 隐藏Bootstrap模态框
        const modalInstance = bootstrap.Modal.getInstance(loadingModal);
        if (modalInstance) {
            modalInstance.hide();
        }
        
        // 强制清理模态框状态
        loadingModal.style.display = 'none';
        loadingModal.classList.remove('show', 'fade');
        loadingModal.setAttribute('aria-hidden', 'true');
        loadingModal.removeAttribute('aria-modal');
    }
    
    // 清理所有模态框背景
    document.querySelectorAll('.modal-backdrop').forEach(backdrop => {
        backdrop.remove();
    });
    
    // 恢复body状态
    document.body.classList.remove('modal-open');
    document.body.style.removeProperty('padding-right');
    document.body.style.removeProperty('overflow');
    document.body.style.removeProperty('padding-left');
}

// 运行PCA分析
function runAnalysis() {
    // 预清理：确保之前的模态框状态被完全清除
    forceHideModal();
    
    // 构建PCA请求数据
    let requestData = {
        analysis_type: 'pca'
    };
    
    // 获取PCA参数
    const nComponents = document.getElementById('nComponents').value;
    if (nComponents) {
        requestData.n_components = parseInt(nComponents);
    }
    
    const varianceThreshold = document.getElementById('varianceThreshold').value;
    if (varianceThreshold) {
        requestData.variance_threshold = parseFloat(varianceThreshold);
    }
    
    // 显示加载模态框
    const loadingModal = new bootstrap.Modal(document.getElementById('loadingModal'));
    loadingModal.show();
    
    // 发送请求
    fetch(`/api/advanced/${filename}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
    })
    .then(response => response.json())
    .then(data => {
        // 确保模态框被隐藏
        forceHideModal();
        
        console.log('Analysis response:', data); // 调试信息
        console.log('Analysis type:', requestData.analysis_type);
        
        if (data.error) {
            console.error('Analysis error:', data.error);
            showError(data.error);
        } else {
            console.log('Calling displayPCAResults');
            try {
                currentResults = data;
                displayPCAResults(data, document.getElementById('resultsContainer'));
                document.getElementById('exportBtn').style.display = 'inline-block';
                console.log('displayPCAResults completed successfully');
            } catch (error) {
                console.error('Error in displayPCAResults:', error);
                showError('显示结果时发生错误: ' + error.message);
            }
        }
    })
    .catch(error => {
        // 确保模态框被隐藏
        forceHideModal();
        
        console.error('Analysis error:', error);
        showError('分析过程中发生错误，请稍后重试');
    });
}

// displayResults函数已移除，直接使用displayPCAResults

// 显示PCA结果
function displayPCAResults(results, container) {
    console.log('displayPCAResults called with:', results);
    
    // 确保模态框完全隐藏
    forceHideModal();
    
    try {
        container.innerHTML = `
        <div class="result-section">
            <h6><i class="fas fa-chart-line me-2"></i>主成分分析结果</h6>
            
            <!-- 关键指标 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-value">${results.n_components}</div>
                        <div class="metric-label">主成分数量</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-value">${(results.total_variance_explained * 100).toFixed(1)}%</div>
                        <div class="metric-label">总解释方差</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-value">${results.n_features}</div>
                        <div class="metric-label">原始特征数</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="metric-card">
                        <div class="metric-value">${results.n_samples}</div>
                        <div class="metric-label">样本数量</div>
                    </div>
                </div>
            </div>
            
            <!-- 可视化图表 -->
            <div class="row">
                <div class="col-md-6">
                    <div id="pcaScatterPlot" class="plot-container"></div>
                </div>
                <div class="col-md-6">
                    <div id="variancePlot" class="plot-container"></div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div id="cumulativePlot" class="plot-container"></div>
                </div>
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">特征重要性</h6>
                        </div>
                        <div class="card-body feature-importance">
                            ${generateFeatureImportanceHTML(results.feature_importance)}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
        // 绘制图表
        if (results.plots) {
            console.log('Drawing plots:', Object.keys(results.plots));
            if (results.plots.pcaPlot) {
                Plotly.newPlot('pcaScatterPlot', results.plots.pcaPlot.data, results.plots.pcaPlot.layout);
            }
            if (results.plots.variancePlot) {
                Plotly.newPlot('variancePlot', results.plots.variancePlot.data, results.plots.variancePlot.layout);
            }
            if (results.plots.cumulativePlot) {
                Plotly.newPlot('cumulativePlot', results.plots.cumulativePlot.data, results.plots.cumulativePlot.layout);
            }
        } else {
            console.warn('No plots data available');
        }
        
        console.log('displayPCAResults completed successfully');
    } catch (error) {
        console.error('Error in displayPCAResults:', error);
        container.innerHTML = '<div class="alert alert-danger">显示PCA结果时发生错误: ' + error.message + '</div>';
    }
}

// 生成特征重要性HTML
function generateFeatureImportanceHTML(importance) {
    if (!importance) return '<p class="text-muted">无特征重要性数据</p>';
    
    const maxValue = Math.max(...Object.values(importance));
    let html = '';
    
    Object.entries(importance)
        .sort(([,a], [,b]) => b - a)
        .slice(0, 10) // 只显示前10个
        .forEach(([feature, value]) => {
            const percentage = (value / maxValue * 100);
            html += `
                <div class="feature-item">
                    <div class="flex-grow-1">
                        <div class="d-flex justify-content-between">
                            <span class="fw-medium">${feature}</span>
                            <span class="text-muted">${value.toFixed(3)}</span>
                        </div>
                        <div class="progress mt-1" style="height: 4px;">
                            <div class="progress-bar" style="width: ${percentage}%"></div>
                        </div>
                    </div>
                </div>
            `;
        });
    
    return html;
}

// 其他显示函数已移除，只保留PCA分析

// 显示错误
function showError(message) {
    const container = document.getElementById('resultsContainer');
    container.innerHTML = `
        <div class="alert alert-danger" role="alert">
            <i class="fas fa-exclamation-triangle me-2"></i>
            <strong>分析失败:</strong> ${message}
        </div>
    `;
}

// 导出结果
function exportResults() {
    if (!currentResults) {
        alert('没有可导出的结果');
        return;
    }
    
    const dataStr = JSON.stringify(currentResults, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `advanced_analysis_${filename}_${new Date().toISOString().slice(0, 10)}.json`;
    link.click();
    
    URL.revokeObjectURL(url);
}
</script>
{% endblock %}